<template>
	<view>
		<view
			class="product-card" 
			>
			<view class="shop-left" style="display: flex; align-items: center;">
				<image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_icon.png" style="width: 50px;" mode="widthFix"></image>
			</view>
			<view class="shop-right">
				<view class="shop-name" style="font-size: 24px;">{{ shop.name }} 
				</view>
				<view class="shop-tags">
					<text class="tag" style="color: #B9751C;background-color: #FDE6C8;">{{ shop.tag1 || '清晰' }}</text>
					<text class="tag" style="color: #2D7D9D;background-color: #C9E8F5;">{{ shop.tag2 || '控轴' }}</text>
					<text class="tag" style="color: #1A918A;background-color: #C6E6E9;">{{ shop.tag3 || '舒适' }}</text>
				</view>
				<view class="shop-time" style="color:#EBA540;">
					<image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_lock.png" class="text-icon"  mode="widthFix"></image>
					<text class="iconfont icon-clock"></text> 接诊时间： {{ shop.acceptTime || '周一至周日 10:00-20:00' }}</view>
				<view class="shop-address" style="color: #B4B4B4;">
					<image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_location.png" class="text-icon"  mode="widthFix"></image>
					<text class="iconfont icon-map"></text> {{ shop.address }}
				</view>
			</view>
		</view>
		 <!-- 日历选择区域 -->
		 <view class="calendar-section">
        <!-- 日历头部保持不变 -->
        <!-- <view class="calendar-header">
          <view class="calendar-controls">
            <image @tap.stop="prevMonth" class="month-btn" style="width: 40px;" src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/cityPoster/prev.svg" mode="widthFix"></image>
            <view class="calendar-month-title">
              {{ currentMonthYear }}
            </view>
            <image @tap.stop="nextMonth" class="month-btn" style="width: 40px;" src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/cityPoster/next.svg" mode="widthFix"></image>
          </view>
        </view> -->
        
        <!-- 添加横向滚动容器 -->
        <view class="calendar-row-container">
          <view class="date-grid">
            <!-- 生成日期方格 -->
            <view 
              v-for="day in availableDates"   
              :key="day.date"
              class="date-cell"
              :class="{
                'selected': selectedDate === day.date,
                'disabled': !day.canAppoint
              }"
              @tap="selectDate(day)"
            >
              <view class="date-day">{{ day.day }}</view>
              <view class="date-week">周{{ getWeekdayText(day.date) }}</view>
              <view v-if="isCurrentDay(day.date)" style="font-size: 10px; margin-top: 2px;">今天</view>
            </view>
          </view>
        </view>
      </view>
		<!-- 时间选择区域 -->
		<view class="time-section">
		<!-- <view class="time-section-title">
			<image src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/cityPoster/appoint_calendar.png" class="time-icon" mode="widthFix"></image>
			日期：{{ selectedDate }} 
			<image src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/cityPoster/calendar_down.png" class="calendar-down" mode="widthFix"></image>
		</view> -->
		<view class="time-section-title">
			<image src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/cityPoster/appoint_clock.png" class="time-icon" mode="widthFix"></image>
			选择时间
		</view>

			<view class="time-period">
				<view class="time-slots">
				<view 
					v-for="slot, key in morningSlots" 
					:key="slot.id"
					class="time-slot"
					:class="{ 
						'selected': selectedTimeSlot === slot.timeSlot,
						'disabled': !slot.canAppoint
					}"
					@click="selectTimeSlot(key)"
				>
					{{ slot.timeText }}
					<view class="slot-status">
						<template>{{slot.showText}}</template>
					</view>
				</view>
				</view>
			</view>
			<view class="confirm-btn" @click="confirmAppoint()">确认预约</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				shop: [],
				shopId: '',
				startDate: '',
				endDate: '',
				// 日历相关
				currentMonthYear: '', // 当前年月
				showCalendar: false, // 日历是否展开
				currentDate: new Date(), // 当前日期
				selectedDate: '', // 选中的日期
				currentDateStr: '', // 当前日期字符串
				weekdays: ['日', '一', '二', '三', '四', '五', '六'], // 星期几
				currentMonthDays: [], // 当前月的日期列表
				prevMonthDays: 0, // 上个月需要显示的日期数量
				nextMonthDays: 0, // 下个月需要显示的日期数量
				
				// 时间选择相关
				morningSlots: [], // 上午时间段
				afternoonSlots: [], // 下午时间段
				selectedTimeSlot: '', // 选中的时间段ID
        availableDates: []
			}
		},
		onLoad(options) {
			this.shopId = options.shopId
			this.startDate = options.startDate
			this.endDate = options.endDate
			// 初始化数据
      		this.initData();
		},
		methods: {
			// 初始化数据
			initData() {
				// 获取店铺信息
				this.getShopInfo();
				
				
				
				// 默认选择今天
				// 查看今天是否在startDate和endDate之中，如果在则显示今天，如果不在则显示startDate
				const today = this.formatDate(this.currentDate);
				if (today >= this.startDate && today <= this.endDate) {
					this.selectedDate = today;
				} else {
					this.currentDate = new Date(this.startDate)
					this.selectedDate = this.startDate;
				}
				console.log('today', today, this.selectedDate)
				this.currentDateStr = this.formatDisplayDate(this.selectedDate);
				
				// 获取今天的预约信息
				this.getAppointmentInfo(this.selectedDate);

				// 初始化日历
				this.initCalendar();
			},
			getShopInfo() {
				const that = this
				try {
					this.$http.GET('/app/order/order/getShopInfo', {
						id: this.shopId
					}, function (res) {
						that.shop = res.data
					})
				} catch (error) {
					console.error('获取店铺列表失败:', error)
				}
			},
			// 切换到上个月
			prevMonth() {
				this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 1, 1);
				this.initCalendar();
			},
			
			// 切换到下个月
			nextMonth() {
				this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1);
				this.initCalendar();
			},
      getWeekdayText(dateStr) {
        const date = new Date(dateStr);
        return this.weekdays[date.getDay()];
      },
			// 初始化日历
			initCalendar() {
				// 根据选择的日期计算当前月
				const year = this.currentDate.getFullYear();
				const month = this.currentDate.getMonth();
				
				// 设置当前年月显示文本
				this.currentMonthYear = `${year}年${month + 1}月`;
				
				// 获取当月第一天
				const firstDay = new Date(year, month, 1);
				// 获取当月最后一天
				const lastDay = new Date(year, month + 1, 0);
				
				// 获取当月第一天是星期几
				const firstDayOfWeek = firstDay.getDay();
				// 获取当月的天数
				const daysInMonth = lastDay.getDate();
				
				// 计算上个月需要显示的天数
				this.prevMonthDays = firstDayOfWeek;
				
				// 计算下个月需要显示的天数
				const totalDaysToShow = 42; // 6行7列 = 42天
				this.nextMonthDays = totalDaysToShow - (firstDayOfWeek + daysInMonth);
				
				// 生成当月的日期列表
				this.currentMonthDays = [];
				for (let i = 1; i <= daysInMonth; i++) {
				const date = new Date(year, month, i);
				const dateStr = this.formatDate(date);
				const today = this.formatDate(new Date());
				
				// 判断是否可以预约（示例逻辑：日期内可以预约，日期外不能预约）
				// 如果开始日期小于今天日期则开始日期改为今天
				if (this.startDate < today) {
					this.startDate = today;
				}
				const canAppoint = dateStr >= this.startDate && dateStr <= this.endDate;
				
				this.currentMonthDays.push({
						date: dateStr,
						day: i,
						disabled: !canAppoint
					});
				}
        // 生成可预约的日期列表（从startDate到endDate）
        this.availableDates = [];
        const start = new Date(this.startDate);
        const end = new Date(this.endDate);
        
        // 遍历从startDate到endDate的所有日期
        let currentDate = new Date(start);
        while (currentDate <= end) {
          const dateStr = this.formatDate(currentDate);
          const today = this.formatDate(new Date());
          const canAppoint = dateStr >= this.startDate && dateStr <= this.endDate;
          
          this.availableDates.push({
            date: dateStr,
            day: currentDate.getDate(),
            canAppoint: canAppoint
          });
          
          // 移动到下一天
          currentDate.setDate(currentDate.getDate() + 1);
        }
			},
			// 格式化日期为YYYY-MM-DD
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			// 格式化显示日期为MM-DD 周X
			formatDisplayDate(dateStr) {
				const date = new Date(dateStr);
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const weekDay = this.weekdays[date.getDay()];
				return `${month}-${day} 周${weekDay}`;
			},
			
			// 判断是否是今天
			isCurrentDay(dateStr) {
				return dateStr === this.formatDate(new Date());
			},
			
			// 切换日历显示/隐藏
			toggleCalendar() {
				this.showCalendar = !this.showCalendar;
			},
			
			// 选择日期
			selectDate(day) {
				if (day.disabled) return;
				
				this.selectedDate = day.date;
				this.currentDateStr = this.formatDisplayDate(day.date);
				this.showCalendar = false;
				
				// 请求该日期的预约信息
				this.getAppointmentInfo(day.date);
			},
			
			// 获取预约信息
			getAppointmentInfo(date) {
				const that = this;
				try {
				this.$http.GET('/app/order/order/getAppointmentInfo', {
						shopId: this.shopId,
						date: date
					}, function (res) {
						// 处理返回的时间段数据
						that.processTimeSlots(res.data);
					})
				} catch (error) {
					console.error('获取预约信息失败:', error);
					// 如果请求失败，显示默认数据
					that.setDefaultTimeSlots();
				}
			},
			
			// 处理时间段数据
			processTimeSlots(data) {
				// 清空之前的时间段
				this.morningSlots = [];
				this.selectedTimeSlot = '';
				
				// 示例数据处理逻辑，实际应根据接口返回的数据结构调整
				console.log('data.appointmentInfo', data.appointmentInfo)
				if (data && data.appointmentInfo) {
					data.appointmentInfo.forEach(item => {
						this.morningSlots.push({
							showText: item.showText,
							timeText: item.timeText,
							canAppoint: item.canAppoint,
							appointed: item.appointed,
							timeSlot: item.timeSlot
						})
					})
				}
				
			},
			
			// 选择时间段
			selectTimeSlot(key) {
				const slot = this.morningSlots[key]
				console.log('selectTimeSlot', slot)
				// 只有可用状态的时间段才能被选择
				if (!slot.canAppoint) return;
				
				this.selectedTimeSlot = slot.timeSlot;
				
				// 这里可以添加选择时间段后的逻辑，比如显示确认按钮等
				console.log('选择了时间段:', slot.timeSlot);
			},
			confirmAppoint() {
				const that = this
				if (!this.selectedTimeSlot) {
					uni.showToast({
						title: '请选择时间',
						icon: 'none'
					})
					return;
				}
				// 确认预约
				this.$http.POST('/app/order/order/appoint', {
					shopId: this.shopId,
					date: this.selectedDate,
					time: this.selectedTimeSlot
				}, function (res) {
					if (res.code === 1000) {
						uni.showModal({
							title: '恭喜你预约成功！',
							content: `您已成功预约${that.shop.name}，日期：${that.selectedDate}，时间：${that.selectedTimeSlot}`,
							showCancel: false,
							success(res) {
								if (res.confirm) {
									// 重置选择状态
									that.selectedTimeSlot = '';
									that.getAppointmentInfo(that.selectedDate);
									// 可以选择跳转到订单列表页面
									// that.$tools.routerTo('/pages/index/orderList', 'navigateTo', 'none');
								}
							}
						});
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				}, function (res) {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				})
			}
		}
	}
</script>

<style>
.text-icon {
  width: 15px;
  margin-right: 5px;
}
.banner {
  width: 100%;
}
.container {
  width: 100%; /* 宽度铺满屏幕 */
  height: 100vh; /* 高度铺满视口 */
  min-height: 100%; /* 确保至少填满内容高度 */
  background-color: #F9F9F9; /* 背景颜色 */
  margin: 0; /* 移除默认外边距 */
  padding: 0; /* 移除默认内边距 */
  box-sizing: border-box; /* 确保内边距和边框不增加总宽度 */
  /* 移除顶部内边距，因为城市栏不再固定在顶部 */
}

/* 城市栏容器 - 用于控制城市栏的位置 */
.city-bar-container {
  width: 100%;
  padding: 16rpx 20rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between; /* 两端对齐 */
  align-items: center; /* 垂直居中 */
}

/* 顶部城市栏样式 */
.city-bar {
  /* 移除固定定位 */
  background-color: #ffffff;
  padding: 10rpx 20rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  margin-left: auto;
}

.location-icon {
  margin-top: 1vw;
  width: 201px;
  object-fit: contain;
}

.city-text {
  font-size: 28rpx;
  color: #333333;
}

.product-card {
    padding: 15px;
    border-radius: 10px;
    margin: 10px;
    display: flex;
    background-color: #ffffff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden; /* 添加这一行，确保内容不会溢出容器 */
    position: relative; /* 添加相对定位，用于对号图片的绝对定位 */
}

/* 添加选中样式 */
.selected-card {
    border: 2px solid #00C853; /* 绿色边框 */
}

.shop-right {
    flex: 1; /* 添加这一行，让shop-right占据剩余空间 */
    padding-left: 10px; /* 添加一些左边距，使内容不紧贴着图片 */
}

.shop-name {
    font-size: 18px;
    margin-bottom: 5px;
    font-weight: bold;
    color: #333;
    word-break: break-all; /* 添加这一行，确保长名称能够换行 */
}

.shop-address {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    font-size: 14px;
    color: #666;
    word-break: break-all; /* 添加这一行，确保长地址能够换行 */
}

.shop-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.shop-name {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.shop-tags {
    display: flex;
    gap: 5px;
    margin-bottom: 5px;
}

.tag {
    background-color: #e6f7ff;
    color: #1890ff;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
}

.shop-info {
    margin-bottom: 15px;
}

.shop-time, .shop-address, .shop-distance {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    font-size: 14px;
    color: #666;
}

.shop-info .iconfont {
    margin-right: 5px;
    color: #1890ff; 
}

.location-container {
    display: flex;
    justify-content: flex-end;
}

.location-btn {
    background-color: #1890ff;
    color: white;
    border: none;
    padding: 6px 15px;
    border-radius: 20px;
    font-size: 14px;
}

/* 城市选择弹窗样式 */
.city-selector-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.city-selector {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 1000;
  max-height: 70vh;
  overflow: hidden;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eeeeee;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.close-btn {
  font-size: 40rpx;
  color: #999999;
}

.city-list {
  padding: 20rpx;
  max-height: calc(70vh - 80rpx);
  overflow-y: auto;
}

.city-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  font-size: 28rpx;
  color: #333333;
}

.city-item:active {
  background-color: #f5f5f5;
}

/* 容器样式 */
  .appoint-container {
    width: 100%;
    min-height: 100vh;
    background-color: #F9F9F9;
    padding-bottom: 20px;
  }
  
  /* 顶部导航栏 */
  .nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 44px;
    background-color: #2E8B57;
    color: white;
    padding: 0 15px;
  }
  
  .back-btn {
    font-size: 18px;
  }
  
  .nav-title {
    font-size: 18px;
    font-weight: bold;
  }
  
  /* 店铺信息卡片 */
  .shop-card {
    display: flex;
    padding: 15px;
    background-color: #fff;
    margin: 10px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }
  
  .shop-left {
    margin-right: 10px;
  }
  
  .shop-right {
    flex: 1;
  }
  
  .shop-name {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  
  .tag {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    margin-left: 8px;
  }
  
  .tag-clear {
    background-color: #FDE6C8;
    color: #B9751C;
  }
  
  .tag-control {
    background-color: #C9E8F5;
    color: #2D7D9D;
  }
  
  .tag-comfort {
    background-color: #C6E6E9;
    color: #1A918A;
  }
  
  .shop-time {
    color: #EBA540;
    font-size: 14px;
  }
  
  /* 日历区域 */
.calendar-section {
  background-color: #fff;
  margin: 10px;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.calendar-controls {
  display: flex;
  align-items: center;
}

.month-btn {
  font-size: 20px;
  padding: 0 10px;
  color: #666;
}

.calendar-month-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 10px;
}

.calendar-content {
  padding-top: 15px;
}

/* 修改为横向滚动的日期选择条 */
.calendar-scroll-container {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 10px;
}

.calendar-scroll-container::-webkit-scrollbar {
  height: 4px;
}

.calendar-scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.calendar-scroll-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 2px;
}

.calendar-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.calendar-row-container {
  padding-bottom: 10px;
  width: 100%;
}

/* 修改为横向排列的日期方格 */
.date-grid {
  display: flex;
  gap: 8px;
  padding-right: 10px;
}

.date-cell {
  flex: 1; /* 让每个日期单元格平均分配宽度 */
  min-width: 0; /* 移除最小宽度限制 */
  max-width: calc(100% / 7); /* 限制最大宽度为容器的1/7 */
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 8px 2px; /* 减少内边距 */
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.date-cell:hover {
  background-color: #e8f5e8;
}

.date-cell.selected {
  background-color: #00C853;
  color: white;
}

.date-cell.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background-color: #f0f0f0;
}

.date-day {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 2px;
}

.date-week {
  font-size: 11px;
  color: #666;
}

.date-cell.selected .date-week {
  color: rgba(255, 255, 255, 0.9);
}
  
  /* 时间选择区域 */
  .time-section {
    background-color: #fff;
    margin: 10px;
    border-radius: 10px;
    padding: 15px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }
  
  .time-section-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
  }
  
  .time-icon {
    width: 16px;
    height: 16px;
    margin-right: 5px;
  }

  .calendar-down {
	width: 10px;
	margin-left: 5px;
  }
  
  .time-period {
    margin-bottom: 20px;
  }
  
  .period-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
  }
  
  .time-slots {
    display: flex;
    flex-wrap: wrap;
  }
  
  .time-slot {
    width: 30%;
    padding: 10px;
    margin: 5px;
    border: 1px solid #ddd;
    border-radius: 5px;
    text-align: center;
	font-size: 28rpx;
  }
  
  .time-slot.selected {
    border-color: #00C853;
    background-color: #F0FFF4;
  }
  
  .time-slot.disabled {
    background-color: #FFC1C1;
	color: #333333;
  }

  .time-slot2.disabled {
    background-color: #FFC1C1;
    color: #333333;
  }
  
  .slot-status {
    font-size: 12px;
    margin-top: 5px;
  }
  
.page-content {
    padding-bottom: 80px; /* 为底部按钮留出空间 */
  }
  
  /* 悬浮底部的确认按钮容器 */
  .bottom-confirm-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(255, 255, 255, 0.95);
    padding: 15px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 999;
  }
  
  /* 确认按钮样式 */
  .confirm-btn {
    background-color: #00C853;
    color: #fff;
    padding: 15px 20px;
    border-radius: 8px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
</style>
